package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.User;
import com.bookstore.back.mapper.UserMapper;
import com.bookstore.back.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 *
 * @author 程序猿_Ti
 * @since 2025-07-19
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public IPage<User> getUserList(Map<String, Object> params) {
        // 分页参数
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());
        
        // 查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        // 用户名搜索
        String username = (String) params.get("username");
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        
        // 邮箱搜索
        String email = (String) params.get("email");
        if (StringUtils.isNotBlank(email)) {
            queryWrapper.like("email", email);
        }
        
        // 手机号搜索
        String phone = (String) params.get("phone");
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.like("phone", phone);
        }
        
        // 状态筛选
        String statusStr = (String) params.get("status");
        if (StringUtils.isNotBlank(statusStr)) {
            Integer status = Integer.parseInt(statusStr);
            queryWrapper.eq("status", status);
        }

        // 性别筛选
        String genderStr = (String) params.get("gender");
        if (StringUtils.isNotBlank(genderStr)) {
            Integer gender = Integer.parseInt(genderStr);
            queryWrapper.eq("gender", gender);
        }

        // 角色筛选
        String roleIdStr = (String) params.get("role_id");
        if (StringUtils.isNotBlank(roleIdStr)) {
            Long roleId = Long.parseLong(roleIdStr);
            queryWrapper.eq("role_id", roleId);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");
        
        return this.page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public boolean createUser(User user) {
        log.info("创建用户前，roleId={}", user.getRoleId());

        // 设置默认值
        if (user.getStatus() == null) {
            user.setStatus(1); // 默认正常状态
        }
        if (user.getBalance() == null) {
            user.setBalance(BigDecimal.ZERO);
        }
        if (user.getGender() == null) {
            user.setGender(0); // 默认未知
        }
        if (user.getRoleId() == null) {
            user.setRoleId(3L); // 默认普通用户角色
            log.warn("roleId为null，设置为默认值3（普通用户）");
        }

        log.info("创建用户后，最终roleId={}", user.getRoleId());
        return this.save(user);
    }

    @Override
    public boolean updateUser(Long userId, User user) {
        user.setId(userId);
        return this.updateById(user);
    }

    @Override
    public boolean deleteUser(Long userId) {
        return this.removeById(userId);
    }

    @Override
    public boolean toggleUserStatus(Long userId, Integer status) {
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        return this.updateById(user);
    }

    @Override
    public boolean batchDeleteUsers(List<Long> userIds) {
        return this.removeByIds(userIds);
    }

    @Override
    public Map<String, Object> getUserStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总用户数
        long totalUsers = this.count();
        stats.put("totalUsers", totalUsers);
        
        // 正常用户数
        QueryWrapper<User> activeWrapper = new QueryWrapper<>();
        activeWrapper.eq("status", 1);
        long activeUsers = this.count(activeWrapper);
        stats.put("activeUsers", activeUsers);
        
        // 禁用用户数
        QueryWrapper<User> disabledWrapper = new QueryWrapper<>();
        disabledWrapper.eq("status", 0);
        long disabledUsers = this.count(disabledWrapper);
        stats.put("disabledUsers", disabledUsers);
        
        return stats;
    }

}
